'use strict';
const Service = require('egg').Service;
const { v4: uuidv4 } = require('uuid');
class PageService extends Service {
    async createToken(id) {
        const { app } = this;
        const token = uuidv4().replace(/-/g, '');
        const tokenObj = {
            id: id,
            token,
            overdue: new Date().getTime() + 7 * 24 * 60 * 60 * 1000
        }
        // 删除旧的id的token
        await app.mysql.delete('hsk_token', { id });
        const result = await app.mysql.insert('hsk_token', tokenObj);
        return result.affectedRows === 1 ? token : null;
    }

    async findUserByToken(token) {
        const { app } = this;
        const whereObj = { token }
        const tokenList = await app.mysql.select('hsk_token', { where: whereObj });
        const tokenObj = tokenList? tokenList[0] : null;
        if (!tokenObj || new Date().getTime() > tokenObj.overdue) {
            return false;
        }else {
            const userList = await app.mysql.select('hsk_user', { where: { id: tokenObj.id } });
            return userList ? userList[0] : null;
        }
    }

}
module.exports = PageService;
